#!/bin/bash

set +x

LOG_PATH=/home/nvidia/positec/robot_logs/
LOG_NAME=sys.log
LOG_MAX_MB=1
INTERVAL=1


disp_date(){
	printf "%s\t" `date "+%D-%T"`	
}

disp_mem(){
 	free -m | awk 'NR==2 {printf "%s/%sMB (%.1f%%)\t", $3,$2,$3*100/$2}'
}

disp_storage(){
	df -h | awk '$NF=="/" {printf "%.1f/%.1fGB (%s)\t", $3,$2,$5}'
}

disp_cpu(){
	uptime | awk '{printf "%.2f/%s\t\t\t", $9, '`nproc`'}'
	top -b -i -c -n5 -d.2 | grep "Cpu" | tail -n1 | awk '{printf "%.1f%%", 100-$(NF-9)}'
}

echo_banner(){
	printf "Time\t\t\tMem\t\t\tStorage\t\t\tLoad\t\t\tUsage\n"
}

check_size(){
	size=`ls -l ${LOG_PATH}/${LOG_NAME} | awk '{ print $5 }' `
	limit=`expr $LOG_MAX_MB \* 1024 \* 1024`
	if [ ${size} -gt ${limit} ]; then
		echo "LOG FILE EXCEED MAX SIZE"
		rm -rf ${LOG_PATH}/${LOG_NAME}
		sync
	fi
}

disp_info()
{
	disp_date
	disp_mem
	disp_storage
	disp_cpu
	echo
}

echo "$0 PID:$$"
while true
do
	if [ ! -f ${LOG_PATH}/${LOG_NAME} ]; then
		echo_banner 1>${LOG_PATH}/${LOG_NAME}
	fi
	sleep ${INTERVAL}
	disp_info 1>>${LOG_PATH}/${LOG_NAME}
	check_size
done

